<template>
  <div class="container ml-3">
    <!-- Note: I've added a :key to the el-form to help with re-rendering when data loads, which can prevent some edge cases -->
    <el-form :key="formKey" label-position="left" ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
      <el-form-item label="报警输入号" label-width="120px">
        <select v-model="form.ioPort" placeholder="">
          <option v-for="item in alarmInOptions" :key="item.portNo" :label="'A<-' + item.portNo" :value="item.portNo"></option>
        </select>
      </el-form-item>
      <el-form-item label="IO端口类型" label-width="120px">
        <select v-model="form.ioSwitchType" placeholder="">
          <option label="常开" :value="1"></option>
          <option label="常闭" :value="0"></option>
        </select>
      </el-form-item>
      <el-checkbox v-model="form.enable" :true-label="1" :false-label="0">处理报警输入</el-checkbox>
    </el-form>

    <el-tabs type="card" class="mt-4" v-model="activeName">
      <el-tab-pane label="布防时间" name="f">
        <timeChoose ref="timeChoose" :initialSchedule="schedule"></timeChoose>
      </el-tab-pane>
      <el-tab-pane label="联动方式" name="s">
        <para ref="liandong" :para="para"></para>
      </el-tab-pane>
    </el-tabs>
    <el-button @click="save" id="submit" class="!mt-8" type="primary" style="margin-left: 0px; width: 120px">保存</el-button>
  </div>
</template>

<script>
import timeChoose from '@/views/components/time.vue';
import para from "@/views/mini/alarm-management/index.vue"
import {
  getAlarmInConfig,
  getAlarmInScheduleConfig,
  getAlarmInTrigger,
  postAlarmInConfig,
  postAlarmInScheduleConfig,
  postAlarmInTrigger
} from "@/api/api2";

export default {
  name: 'index',
  components: {
    timeChoose,
    para
  },
  data() {
    return {
      title: "",
      schedule: [],
      open: false,
      activeName: 'f',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      radio: '1',
      alarmInOptions: [],
      formKey: Date.now(),
      // 表单参数
      form: {
        enable: 0,
        ioPort: null,
        ioSwitchType: null,
      },
      para: {
        uploadCenter: 0,
        "linkage": [
          {"portNo": 1, "output": 1,},
          {"portNo": 2, "output": 1,},
        ]
      },
      rules: {},
    }
  },
  watch: {
    // This watcher is correct. It updates the form when the selected port changes.
    'form.ioPort'(newPortNo, oldPortNo) {
      if (newPortNo) {
        const selectedOption = this.alarmInOptions.find(item => item.portNo === newPortNo);
        if (selectedOption) {
          // This updates the 'ioSwitchType' dropdown to reflect the selected port's current type.
          // This will also trigger the watcher below, but that's okay.
          this.form.ioSwitchType = selectedOption.switchType;
        }
      }
    },

    'form.ioSwitchType'(newSwitchType) {
      // Guard condition: Only proceed if there is a port selected.
      if (this.form.ioPort === null) {
        return;
      }

      // Find the object in the master array that corresponds to the currently selected port.
      const targetOption = this.alarmInOptions.find(item => item.portNo === this.form.ioPort);

      // If we found the object and its type is different from the new type, update it.
      if (targetOption && targetOption.switchType !== newSwitchType) {
        targetOption.switchType = newSwitchType;
      }
    }
  },
  created() {
    let res =  {
      "code": 0,
      "msg": "ok",
      "data": {
        "enable": 0,
        "alarmIn": [
          {
            "portNo": 1,
            "switchType": 0,
            "name": "报警输入1",
          },
          {
            "portNo": 2,
            "switchType": 1,
            "name": "报警输入2",
          },
        ]
      }
    }
    getAlarmInConfig().then(res => {
      if (res.code === 0 && res.data && res.data.alarmIn) {
      this.alarmInOptions = res.data.alarmIn;
      this.form.enable = res.data.enable;
      if (this.alarmInOptions.length > 0) {
        const firstOption = this.alarmInOptions[0];
        this.form.ioPort = firstOption.portNo;
        // The 'form.ioPort' watcher will automatically set the initial ioSwitchType
      }
      this.formKey = Date.now();
      } else {
        this.$message.error("获取报警输入配置失败");
      }
    });

    // The rest of your created hook is fine
    getAlarmInScheduleConfig().then(res => {
      if (res.code === 0) {
        this.schedule = res.data.daySchedules;
      } else {
        this.$message.error("获取布防时间配置失败");
      }
    });

    getAlarmInTrigger().then(res => {
      if (res.code === 0) {
        this.para = res.data;
      } else {
        this.$message.error("获取联动方式配置失败");
      }
    });
  },
  methods: {
    save() {
      // --- Time Schedule and Trigger Saving (Unchanged) ---
      if (this.activeName == 'f') {
        let form = this.$refs.timeChoose.form.scheduleAction;
        postAlarmInScheduleConfig({
          type: 'alarmIn',
          daySchedules: form
        }).then(res => {
          if (res.code === 0) {
            this.$message.success("布防时间保存成功");
          } else {
            this.$message.error("布防时间保存失败");
          }
        })
      } else {
        let form2 = this.$refs.liandong.form;
        postAlarmInTrigger(form2).then(res => {
          if (res.code === 0) {
            this.$message.success("联动方式保存成功");
          } else {
            this.$message.error("联动方式保存失败");
          }
        })
      }

      // --- Alarm Input Config Saving (SIMPLIFIED) ---
      // Because the new watcher keeps `alarmInOptions` always up-to-date,
      // we no longer need to manually update it here. We can just send it.

      const payload = {
        enable: this.form.enable,
        alarmIn: this.alarmInOptions // Send the entire list, which is now always correct.
      };

      postAlarmInConfig(payload).then(res => {
        if (res.code === 0) {
          this.$message.success("报警输入配置保存成功");
        } else {
          this.$message.error("报警输入配置保存失败");
        }
      })
    },
  }
}
</script>

<style scoped>
/* Your existing styles are fine, no changes needed here */
.container {
  /*//margin-left: 15%;*/
  /*//margin-top: 5%;*/
}

.week-schedule {
  display: flex;
  flex-wrap: wrap;
  gap: 80px;
  flex-direction: row;
}

.day-schedule {
  flex: 0 0 35%;
  /* Each .day-schedule will try to take up half the width of its container */
  max-width: 50%;
  /* Ensures that the .day-schedule does not exceed half the width */
  box-sizing: border-box;
}

.block {
  display: flex;
  margin-top: 10px;
}

@media (max-width: 600px) {

  /* Adjust the breakpoint as needed */
  .day-schedule {
    flex: 0 0 100%;
    /* On smaller screens, the .day-schedule will take the full width */
    max-width: 100%;
  }
}

.button {
  margin-left: 15%;
}

.el-form-item .el-form-item {
  margin-bottom: 10px;
}

select {
  width: 202px;
}


.title {
  background-color: #F2F2F2;
  font-weight: 700;
  margin-top: 10px;
}

.title {
  background-color: #F2F2F2;
  font-weight: 700;
  padding-left: 15px;
  margin-top: 10px;
  margin-bottom: 5px;
}

.title {
  height: 30px;
  line-height: 30px;
}
</style>
